package com.example.opengl.camera.filter

import android.content.Context
import android.opengl.GLES20
import android.opengl.GLES20.*
import com.example.opengl.R
import com.example.opengl.camera.TextureHelper
import javax.microedition.khronos.opengles.GL

/**
 * @author: Mr.You
 * @create: 2023-10-16 17:50
 * @description:
 **/
open class BaseFrameFilter(fragmentSourceId: Int = R.raw.base_fragment) :
    BaseFilter( fragmentSourceId = fragmentSourceId) {

    //FBO缓冲区
    private var mFragmentBuffers: IntArray? = null

    //FBO的纹理id
    private var mFragmentBufferTexture: IntArray? = null

    override fun onReady(width: Int, height: Int) {
        super.onReady(width, height)
        mFragmentBuffers = intArrayOf(1)
        //创建FBO帧缓冲区
        GLES20.glGenFramebuffers(mFragmentBuffers!!.size, mFragmentBuffers, 0)
        //创建FBO纹理
        mFragmentBufferTexture = intArrayOf(1)
        TextureHelper.getTextures(mFragmentBufferTexture!!)

        //FBO绑定纹理
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mFragmentBufferTexture!![0])

        //生成2D纹理图像
        GLES20.glTexImage2D(
            GLES20.GL_TEXTURE_2D,
            0,
            GLES20.GL_RGBA,
            width,
            height,
            0,
            GLES20.GL_RGBA,
            GLES20.GL_UNSIGNED_BYTE,
            null
        )
        //绑定缓冲区
        glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFragmentBuffers!![0])

        GLES20.glFramebufferTexture2D(
            GLES20.GL_FRAMEBUFFER,
            GLES20.GL_COLOR_ATTACHMENT0,
            GLES20.GL_TEXTURE_2D,
            mFragmentBufferTexture!![0],
            0
        )

        //解绑操作
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0)
        glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0)

    }

    override fun onDrawFrame(textureId: Int): Int {
        //设置显示窗口大小
        glViewport(0, 0, mWidth, mHeight)
        //绑定FBO
        glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFragmentBuffers!![0])
        //使用着色器程序
        GLES20.glUseProgram(mProgramId)
        //赋值给顶点着色器代码
        mVertexBuffer?.position(0)
        GLES20.glVertexAttribPointer(vPosition, 2, GLES20.GL_FLOAT, false, 0, mVertexBuffer)
        GLES20.glEnableVertexAttribArray(vPosition)
        //赋值给纹理着色器代码
        mTextureBuffer?.position(0)
        GLES20.glVertexAttribPointer(vCoord, 2, GLES20.GL_FLOAT, false, 0, mTextureBuffer)
        GLES20.glEnableVertexAttribArray(vCoord)

        //变换矩阵
        GLES20.glActiveTexture(GLES20.GL_TEXTURE_2D)
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId)
        GLES20.glUniform1i(vTexture, 0)
        //启动OpenGL绘制功能
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)

        //解绑
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0)
        glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0)

        return mFragmentBufferTexture!![0]
    }
}